package nio;

import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.List;

/**
 * Created by Administrator on 2017/10/22 022.
 */
public class FileAttributeDemo
{
    public static void main(String[] args) throws Exception
    {
        Path path = Paths.get("D:\\Android\\IdeaProj\\JavaDemo\\src\\main\\java\\nio\\FileAttributeDemo.java");
        BasicFileAttributeView basicView = Files.getFileAttributeView(path, BasicFileAttributeView.class);
        BasicFileAttributes attr = basicView.readAttributes();
        System.out.println("创建时间：" + attr.creationTime());
        System.out.println("修改时间：" + attr.lastModifiedTime());
        System.out.println("文件大小：" + attr.size());
        FileOwnerAttributeView ownerView = Files.getFileAttributeView(path, FileOwnerAttributeView.class);
        System.out.println("文件归属：" + ownerView.getOwner());

        UserPrincipal up = FileSystems.getDefault()
                .getUserPrincipalLookupService()
                .lookupPrincipalByName("guest");
        ownerView.setOwner(up);
        UserDefinedFileAttributeView userView = Files.getFileAttributeView(path, UserDefinedFileAttributeView.class);
        List<String> attrName = userView.list();
        attrName.forEach((s)->
        {
            try
            {
                ByteBuffer bf = ByteBuffer.allocate(userView.size(s));
                userView.read(s, bf);
                bf.flip();
                String value = Charset.defaultCharset().decode(bf).toString();
                System.out.println(s + "-->" + value);
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        });
        userView.write("test" ,Charset.defaultCharset().encode("java string"));
        DosFileAttributeView dosView = Files.getFileAttributeView(path, DosFileAttributeView.class);
        dosView.setHidden(true);
        dosView.setReadOnly(true);
    }
}
